<?php

declare (strict_types=1);

namespace App\Http\Controllers\Api;

/**
 * 加密解密规则
 *
 * Class Aes
 */
class Aes
{
    private string $paddingChar = "\0";
    private mixed $key;
    private mixed $iv;
    private int $option = OPENSSL_ZERO_PADDING;
    private string $method = 'aes-128-cbc';

    /**
     * Aescrypt constructor.
     *
     * @param string $key
     * @param string $iv
     */
    public function __construct(string $key = 'nnNdYE3MftWm5gWn', string $iv = '9mXW4f4fvgSFG0bt')
    {
        $this->key = $key;
        $this->iv = $iv;
    }

    /**
     * @param string $content
     *
     * @return string
     * @desc  aes-128加密
     */
    public function encrypt(string $content): string
    {
        $strLength = strlen($content);
        $content .= str_repeat($this->paddingChar, 16 - $strLength % 16);
        $data = openssl_encrypt($content, $this->method, $this->key, $this->option, $this->iv);
        if (false === $data) {
            echo openssl_error_string();
            exit;
        }

        return $data;
    }

    /**
     * @param string $encryptData
     *
     * @return string
     * @desc aes-128解密
     */
    public function decrypt(string $encryptData): string
    {
        $data = openssl_decrypt($encryptData, $this->method, $this->key, $this->option, $this->iv);

        return substr($data, 0, strpos($data, $this->paddingChar));
    }
}
